/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.zookeeper.server.quorum;

import org.apache.jute.Record;
import org.apache.log4j.Logger;
import org.apache.zookeeper.ZooDefs.OpCode;
import org.apache.zookeeper.proto.PrepareDataRequest;
import org.apache.zookeeper.server.*;
import org.apache.zookeeper.server.paxos2.*;
import org.apache.zookeeper.txn.PrepareDataTxn;
import org.apache.zookeeper.txn.TxnHeader;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * This RequestProcessor forwards any requests that modify the state of the
 * system to the Leader.
 */
public class FollowerRequestProcessor extends Thread implements
        RequestProcessor {
    private static final Logger LOG = Logger.getLogger(FollowerRequestProcessor.class);

    FollowerZooKeeperServer zks;

    RequestProcessor nextProcessor;

    

    LinkedBlockingQueue<Request> queuedRequests = new LinkedBlockingQueue<Request>();

    boolean finished = false;

    public FollowerRequestProcessor(FollowerZooKeeperServer zks,
                                    RequestProcessor nextProcessor) {
        super("FollowerRequestProcessor:" + zks.getServerId());
        this.zks = zks;
        this.nextProcessor = nextProcessor;
       
    }

    @Override
    public void run() {
        try {
            while (!finished) {
                Request request = queuedRequests.take();
                if (LOG.isTraceEnabled()) {
                    ZooTrace.logRequest(LOG, ZooTrace.CLIENT_REQUEST_TRACE_MASK,
                            'F', request, "");
                }
                if (request == Request.requestOfDeath) {
                    break;
                }
                // We want to queue the request to be processed before we submit
                // the request to the leader so that we are ready to receive
                // the response
                if(request.type != OpCode.boloskyGetData && request.cxid > -2 && request.cxid < ReplyCache.getFirstCxid(request.sessionId)){
            	    System.out.println("Old request "+request.sessionId+" "+request.cxid+" first "+ReplyCache.getFirstCxid(request.sessionId));
            	    if(request.type == OpCode.prepareData)
                	Configuration.decreaseOutstanding();
		    continue;	
        }
                ByteBuffer reply = ReplyCache.getReply(request.sessionId, request.cxid);
                if (reply != null) {
                    System.out.println("Retransmit " + request.sessionId + " " + request.cxid);
                    ServerCnxn cnxn = zks.getServerCnxnFactory().getServerCnxn(request.sessionId);
                    ((NIOServerCnxn) cnxn).sendBuffer(reply);
                    if(request.type == OpCode.prepareData)
                	Configuration.decreaseOutstanding();
		    continue;
                }

                if (request.type == OpCode.prepareData) {
                    PrepareDataRequest prepareDataRequest = new PrepareDataRequest();
                    request.request.rewind();
		    prepareDataRequest.setClientId(request.request.getLong());
		    prepareDataRequest.setCount(request.request.getInt());
		    int size = request.request.getInt();
		    if(size!= Configuration.blockSize)
			throw new RuntimeException("mismatch");
    		    byte[] data = MemoryBuffer.allocateBuffer();//new byte[Configuration.blockSize];
		    request.request.get(data);
		    prepareDataRequest.setData(data);

                    //ZooKeeperServer.byteBuffer2Record(request.request,
                    //        prepareDataRequest);
                    //LOG.info("Put " + request.sessionId+" "+request.cxid + " into data cache");
                    PrepareDataCache.put(prepareDataRequest.getClientId(), request.cxid, prepareDataRequest);
                    PrepareDataTxn txn = new PrepareDataTxn(prepareDataRequest.getClientId(), request.cxid, prepareDataRequest.getData());
                    //request.txn = txn;
                    zks.logRequest(new TxnHeader[]{new TxnHeader(prepareDataRequest.getClientId(), request.cxid, request.nonce, -1, zks.getTime(), OpCode.prepareData)}, new Record[]{txn});
                    continue;
                }

                nextProcessor.processRequest(request);

                // We now ship the request to the leader. As with all
                // other quorum operations, sync also follows this code
                // path, but different from others, we need to keep track
                // of the sync operations this follower has pending, so we
                // add it to pendingSyncs.
                switch (request.type) {
                    case OpCode.sync:
                        zks.pendingSyncs.add(request);
                        zks.getFollower().request(request);
                        break;
                    case OpCode.setData:
                        zks.getFollower().request(request);
                        break;
                    case OpCode.boloskyGetData:
                        zks.getFollower().request(request);
                        break;
                }
            }
        } catch (Exception e) {
            LOG.error("Unexpected exception causing exit", e);
        }
        LOG.info("FollowerRequestProcessor exited loop!");
    }

    public void processRequest(Request request) {
//	if(queuedRequests.size()>100)
//	    System.out.println("follower size="+queuedRequests.size());
        if (!finished) {
            queuedRequests.add(request);
        }
    }

    public void processRequest(Request[] request) {
       throw new RuntimeException("Not implemented");
    }

    public void shutdown() {
        finished = true;
        queuedRequests.clear();
        queuedRequests.add(Request.requestOfDeath);
        nextProcessor.shutdown();
    }

}
